package com.example.im.mvp.presenter

import android.content.Context
import com.example.im.bean.UserRoom
import com.example.im.common.Enumerate
import com.example.im.db.DatabaseStorage
import com.example.im.bean.EventBusData
import com.example.im.common.Constants
import com.example.im.xmpp.IMConnection
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IUserView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus

class UserPresenter(mContext: Context, mView: IUserView?) :
    BasePresenter<IUserView>(mContext, mView) {

    private var imConnection: IMConnection? = null

    init {
        imConnection = IMConnection.instance
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    /**
     * 搜索用户
     * */
    fun userSearch(userId: String) {
        if (userId.isEmpty()) {
            getView().onHint("请输入您要搜索的ID")
            return
        }

        val observable = Observable.just(userId)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.getRosterSearch(it)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                if (it.isEmpty())
                    getView().onHint("未找到该用户ID")
                it.isNotEmpty()
            }
            .flatMap {
                Observable.fromIterable(it)
            }
            .filter {
                val userRoom =
                    DatabaseStorage.getUserRoomStorageByAccount(it.getValues("Username")[0].toString())
                if (userRoom == null) {
                    true
                } else {
                    userRoom.sub == Constants.USER_ROOM_SUB_0 || userRoom.sub == Constants.USER_ROOM_SUB_1
                }
            }
            .map {
                with(UserRoom(), {
                    this.jid = it.getValues("jid")[0].toString()
                    this.account = it.getValues("Username")[0].toString()
                    this.nickname = it.getValues("Name")[0].toString()
                    this.getUserRoom()
                })
//                DatabaseStorage.getUserRoomStorageByAccount(it.getValues("Username")[0].toString())
//                    ?: with(UserRoom(), {
//                        this.jid = it.getValues("jid")[0].toString()
//                        this.account = it.getValues("Username")[0].toString()
//                        this.nickname = it.getValues("Name")[0].toString()
//                        this.getUserRoom()
//                    })
            }
            .toList()
            .toObservable()
            .subscribe(
                { getView().onSearchFriendGood(it) },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable)
    }

    /**
     * 添加用户
     * */
    fun userAddition(userName: String, name: String) {
        if (userName.isEmpty()) {
            getView().onHint("用户账号不能为空")
            return
        }
        if (name.isEmpty()) {
            getView().onHint("用户昵称不能为空")
            return
        }

        val observable = Observable.zip(
            Observable.just(userName),
            Observable.just(name),
            BiFunction<String, String, Boolean> { t1, t2 ->
                imConnection!!.setRosterCreate(t1, t2)
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it) {
                        getView().onHint("已发送添加好友请求,请等待对方确认！")
                        getView().onAdditionSuccess()
                    } else getView().onHint("添加失败！")
                },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable)
    }

    /**
     * 删除用户聊天记录
     * */
    fun userDeleteChat(userRoom: UserRoom) {
        //删除数据库数据
        DatabaseStorage.deleteChatRecordStorage(userRoom)
        //通知聊天列表页面更新
        val busData = EventBusData(
            Enumerate.Handle.list_chat, Enumerate.Action.list_delete, userRoom
        )
        EventBus.getDefault().post(busData)

        getView().onRemoverSuccess()
    }

    /**
     * 删除用户
     * */
    fun userDelete(userRoom: UserRoom) {
        val observable = Observable.just(userRoom)
            .subscribeOn(Schedulers.io())
            .map { imConnection!!.removeRosterEntries(userRoom.jid!!) }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (!it) getView().onHint("删除用户失败") else {
//                        //删除数据库数据
//                        DatabaseStorage.deleteUserRoomStorage(userRoom)
//                        //通知聊天列表页面更新
//                        val busData1 = EventBusData(
//                            Enumerate.Handle.list_chat, Enumerate.Action.list_delete, userRoom
//                        )
//                        EventBus.getDefault().post(busData1)
//                        //通知好友列表页面更新
//                        val busData2 = EventBusData(
//                            Enumerate.Handle.list_friend, Enumerate.Action.list_delete, userRoom
//                        )
//                        EventBus.getDefault().post(busData2)

                        getView().onRemoverSuccess()
                    }
                },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable)
    }

}